﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibMinecraft.Server;
using LibMinecraft.Model.Packets;
using System.Xml.Linq;
using System.IO;
using LibMinecraft.Model;

namespace PartyCraftServer.Commands
{
    public class OPCommand : Command
    {
        public override bool RequiresOp
        {
            get { return true; }
        }

        public override string DefaultCommand
        {
            get { return "op"; }
        }

        public override string Documentation
        {
            get { return "Sets [player] to operator status.\nUsage: /op [player]"; }
        }

        public override void ExecuteCommand(RemoteClient client, params string[] parameters)
        {
            if (parameters.Length != 1)
            {
                client.SendChat(ChatColor.Red + "Invalid parameters.  Use /op [player].");
            }
            PartyCraft.SendToOps(ChatColor.Blue + client.PlayerEntity.Name + " has opped " + parameters[0]);
            foreach (RemoteClient c in PartyCraft.Server.ConnectedClients
                .Where(p => p.PlayerEntity.Name == parameters[0]))
            {
                c.Tags["op"] = true;
                c.PacketQueue.Enqueue(new ChatMessagePacket(PartyCraft.Settings["server.messages.op"]));
            }

            if (!File.Exists(Path.Combine(PartyCraft.SettingsDirectory, "players", parameters[0] + ".xml")))
            {
                XDocument d = new XDocument();
                d.Add(new XElement("partycraft"));
                XElement player = new XElement("player");
                XElement subPlayer = new XElement(parameters[0].ToLower());
                subPlayer.Add(new XElement("op", "false"));
                player.Add(subPlayer);
                d.Root.Add(player);

                d.Save(Path.Combine(PartyCraft.SettingsDirectory, "players", parameters[0] + ".xml"));

                PartyCraft.Settings.LoadFile(Path.Combine(PartyCraft.SettingsDirectory, "players", parameters[0] + ".xml"));
            }

            PartyCraft.Settings["player." + parameters[0] + ".op"] = "true";
        }
    }
}
